package com.jincp.filepicker.ui.image;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.jincp.common.permission.MPermission;
import com.jincp.common.utils.AppUtils;
import com.jincp.common.utils.ToastUtil;
import com.jincp.filepicker.Constant;
import com.jincp.filepicker.R;
import com.jincp.filepicker.bean.ImageFile;
import com.jincp.filepicker.base.BasePickerManager;
import com.jincp.filepicker.util.MediaFileUtil;
import com.jincp.filepicker.widgets.CropImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧 Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：图片选择的入口类
 * 修订历史：
 * ================================================
 */
public class ImagePickerManager extends BasePickerManager<ImagePickerManager> {

    public static final String TAG = ImagePickerManager.class.getSimpleName();

    public static final int REQUEST_IMAGE_TAKE = 1001;
    public static final int REQUEST_IMAGE_CROP = 1002;

    public static final int RESULT_IMAGE_ITEMS = 1004;
    public static final int RESULT_IMAGE_ITEM = 1005;

    public static final int FROM_CAMERA = 1;
    public static final int FROM_LOCAL = 2;

    private boolean isNeedImageCrop = false;         //裁剪
    private boolean isShowCamera = true;   //显示相机
    private int outPutX = 800;           //裁剪保存宽度
    private int outPutY = 800;           //裁剪保存高度
    private int focusWidth = 600;         //焦点框的宽度
    private int focusHeight = 600;        //焦点框的高度
    private CropImageView.Style style = CropImageView.Style.RECTANGLE; //裁剪框的形状

    private static volatile ImagePickerManager mInstance;

    private ImagePickerManager() {
    }

    public static ImagePickerManager getInstance() {
        if (mInstance == null) {
            synchronized (ImagePickerManager.class) {
                if (mInstance == null) {
                    mInstance = new ImagePickerManager();
                }
            }
        }
        return mInstance;
    }

    public ImagePickerManager reset() {
        setMultiMode(false);
        setMaxSelectedLimit(9);
        setNeedImageCrop(false);
        setShowCamera(true);
        setOutPutX(800);
        setOutPutY(800);
        setFocusWidth(600);
        setFocusHeight(600);
        setStyle(CropImageView.Style.RECTANGLE);
        return this;
    }

    public ImagePickerManager setNeedImageCrop(boolean needImageCrop) {
        isNeedImageCrop = needImageCrop;
        return this;
    }

    public ImagePickerManager setShowCamera(boolean showCamera) {
        isShowCamera = showCamera;
        return this;
    }

    public ImagePickerManager setOutPutX(int outPutX) {
        this.outPutX = outPutX;
        return this;
    }

    public ImagePickerManager setOutPutY(int outPutY) {
        this.outPutY = outPutY;
        return this;
    }

    public ImagePickerManager setFocusWidth(int focusWidth) {
        this.focusWidth = focusWidth;
        return this;
    }

    public ImagePickerManager setFocusHeight(int focusHeight) {
        this.focusHeight = focusHeight;
        return this;
    }

    public boolean isNeedImageCrop() {
        return isNeedImageCrop;
    }

    public boolean isShowCamera() {
        return isShowCamera;
    }

    public int getOutPutX() {
        return outPutX;
    }

    public int getOutPutY() {
        return outPutY;
    }

    public int getFocusWidth() {
        return focusWidth;
    }

    public int getFocusHeight() {
        return focusHeight;
    }

    public CropImageView.Style getStyle() {
        return style;
    }

    public void setStyle(CropImageView.Style style) {
        this.style = style;
    }

    private File takeImageFile;  //拍照保存照片文件

    public File getTakeImageFile() {
        return takeImageFile;
    }


    /**
     * 拍照的方法
     */
    public void takePicture(Fragment fragment) {
        if (fragment == null) return;
        Activity activity = fragment.getActivity();
        if (activity == null || activity.isFinishing()) return;
        if (isCleanSelectedItem()) {
            clear();
        }
        if (MPermission.hasPermissions(activity, Constant.PERMISSION)) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePictureIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            if (createFile("IMG_", ".jpg")) {
                Uri uri = AppUtils.getFileUri(activity, takeImageFile);
                // 默认情况下，即不需要指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                // 照相机有自己默认的存储路径，拍摄的照片将返回一个缩略图。如果想访问原始图片，
                // 可以通过dat extra能够得到原始图片位置。即，如果指定了目标uri，data就没有数据，
                // 如果没有指定uri，则data就返回有数据！
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                } else {
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                }
            } else {
                ToastUtil.getInstance().show(R.string.create_file_failure);
                return;
            }
            if (MediaFileUtil.detectIntent(activity, takePictureIntent)) {
                fragment.startActivityForResult(takePictureIntent, ImagePickerManager.REQUEST_IMAGE_TAKE);
            } else {
                ToastUtil.getInstance().show(R.string.no_photo_app);
            }
        } else {
            MPermission.with(fragment).permissions(Constant.PERMISSION).request();
        }
    }

    /**
     * 拍照的方法
     */
    public void takePicture(Activity activity) {
        if (activity == null || activity.isFinishing()) return;
        if (isCleanSelectedItem()) {
            clear();
        }
        if (MPermission.hasPermissions(activity, Constant.PERMISSION)) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePictureIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            if (createFile("IMG_", ".jpg")) {
                Uri uri = AppUtils.getFileUri(activity, takeImageFile);
                // 默认情况下，即不需要指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                // 照相机有自己默认的存储路径，拍摄的照片将返回一个缩略图。如果想访问原始图片，
                // 可以通过dat extra能够得到原始图片位置。即，如果指定了目标uri，data就没有数据，
                // 如果没有指定uri，则data就返回有数据！
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                } else {
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                }
            } else {
                ToastUtil.getInstance().show(R.string.create_file_failure);
                return;
            }
            if (MediaFileUtil.detectIntent(activity, takePictureIntent)) {
                activity.startActivityForResult(takePictureIntent, ImagePickerManager.REQUEST_IMAGE_TAKE);
            } else {
                ToastUtil.getInstance().show(R.string.no_photo_app);
            }
        } else {
            MPermission.with(activity).permissions(Constant.PERMISSION).request();
        }
    }


    /**
     * 选择照片的方法
     */
    public void pickPicture(Fragment fragment) {
        if (isCleanSelectedItem()) {
            clear();
        }
        if (MPermission.hasPermissions(fragment.getActivity(), Constant.PERMISSION)) {
            Intent takePictureIntent = new Intent(fragment.getActivity(), ImagePickActivity.class);
            fragment.startActivityForResult(takePictureIntent, ImagePickerManager.REQUEST_IMAGE_TAKE);
        } else {
            MPermission.with(fragment).permissions(Constant.PERMISSION).request();
        }
    }

    /**
     * 选择照片的方法
     */
    public void pickPicture(Activity activity) {
        if (isCleanSelectedItem()) {
            clear();
        }
        if (MPermission.hasPermissions(activity, Constant.PERMISSION)) {
            Intent takePictureIntent = new Intent(activity, ImagePickActivity.class);
            activity.startActivityForResult(takePictureIntent, ImagePickerManager.REQUEST_IMAGE_TAKE);
        } else {
            MPermission.with(activity).permissions(Constant.PERMISSION).request();
        }
    }

    /**
     * 产生一个图片文件
     */
    public boolean createFile(String prefix, String suffix) {
        try {
            takeImageFile = MediaFileUtil.createFile("image", prefix, suffix);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void previewPicture(Activity activity, ImageFile imageFile) {
        Intent previewPictureIntent = new Intent(activity, ImagePreviewActivity.class);
        previewPictureIntent.putExtra(ImagePreviewActivity.IMAGE_FILE, imageFile);
        activity.startActivity(previewPictureIntent);
    }

    public void cropPicture(Activity activity, ImageFile imageFile) {
        //单选需要裁剪，进入裁剪界面
        Intent cropPictureIntent = new Intent(activity, ImageCropActivity.class);
        cropPictureIntent.putExtra(ImageCropActivity.IMAGE_FILE, imageFile);
        activity.startActivityForResult(cropPictureIntent, ImagePickerManager.REQUEST_IMAGE_CROP);
    }

    // 打开摄像头拍照的回调
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        // 裁剪的回调
        if (resultCode == ImagePickerManager.RESULT_IMAGE_ITEM && requestCode == ImagePickerManager.REQUEST_IMAGE_CROP) {
            clear();
            ImageFile image = data.getParcelableExtra(BasePickerManager.EXTRA_RESULT_ITEM);
            addSelectedFile(image);
            completedSelector();
        } else if (resultCode == Activity.RESULT_OK && requestCode == ImagePickerManager.REQUEST_IMAGE_TAKE) {
            ImageFile image = new ImageFile();
            image.setPath(takeImageFile.getAbsolutePath());
            // 是否裁剪
            if (isNeedImageCrop()) {
                cropPicture(activity, image);
            } else {
                clear();
                addSelectedFile(image);
                completedSelector();
            }
            MediaFileUtil.notifyMediaChanged(activity, takeImageFile);
        }
    }
}